import { Axios } from 'axios';
import axios from 'axios';

export class AxiosRetry {
  private fetchNewTokenPromise: Promise<any> | null = null;
  private onSuccess: (res: any) => any;
  private onError: () => any;

  constructor({
    onSuccess,
    onError,
  }: {
    onSuccess: (res: any) => any;
    onError: () => any;
    }) {
    this.onSuccess = onSuccess;
    this.onError = onError;
  }

  /** 发送请求*/
  requestWrapper<T>(request: () => Promise<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      /** 将请求接口的函数保存*/
      const requestFn = request;
      return request().then((res) => {
        //拦截器处理后的数据
        resolve(res);
      }).catch(err => {
        //token过期或者没有token    
        if (err.response.status === 401) {
          if (!this.fetchNewTokenPromise) {
            this.fetchNewTokenPromise = this.fetchNewToken();
          }
          this.fetchNewTokenPromise.then(() => {
            return requestFn();
          }).then((res) => {
            resolve(res);
            this.fetchNewTokenPromise = null;
          }).catch((err) => {
            reject(err);
            this.fetchNewTokenPromise = null;
          });
        } else {
          reject(err);
        }
      });
    });
  }

  // 获取新的token
  fetchNewToken() {
    return axios({
      method: "post",
      url: `/refreshToken`,
    }).then((res) => {
      this.onSuccess(res)
    }).catch((err) => {
      this.onError();
      //表示refreshToken过期，需要重新登录
      if (err.response.status === 401) {
        return Promise.reject(
          new Error("refreshToken过期，需要重新登录")
        );
      }
      //表示发生了其他错误
      else {
        return Promise.reject(err); 
      }
    })
  }
}